import multiprocessing
import sys
import os
from time import sleep
from datetime import datetime, time
from logging import INFO, ERROR

from vnpy.event import EventEngine
from vnpy.trader.setting import SETTINGS
from vnpy.trader.engine import MainEngine

from vnpy.gateway.ctp import CtpGateway
from vnpy.gateway.ctptest import CtptestGateway
from vnpy.gateway.ctp6.4 import CtpGateway4
from vnpy.gateway.ctp6.5 import CtpGateway5
from vnpy.gateway.ctp6 .9 import CtpGateway9

import logging
import pdb
# from vnpy.app.cta_strategy import CtaStrategyApp
from vnpy.app.cta_strategy.base import EVENT_CTA_LOG


# from vnpy.app.data_manager import DataManagerApp
from vnpy.app.data_recorder import DataRecorderApp
from baseSetting import WORKING_DIR, USER_FILE

import sys
# encoding: utf-8
import json

ctp_setting = {
    "用户名": "140589",
    "密码": "bc2021",
    "经纪商代码": "9999",
    "交易服务器": "180.168.146.187:10130",
    "行情服务器": "180.168.146.187:10131",
    "产品名称": "simnow_client_test",
    "授权编码": "0000000000000000",
    "产品信息": "simnow_client"
}


def load_json(jsonfile):
    '''读取json中的数据'''
    try:
        with open(jsonfile, 'r', encoding='utf-8') as f:
            data = json.load(f)
        return data
    except IOError:
        raise


def save_json(data, savepath):
    '''以json格式保存数据到目标路径'''
    with open(savepath, 'w', encoding='utf-8') as f:
        jsonD = json.dumps(data, indent=4)
        f.write(jsonD)


if len(sys.argv) > 1:
    print(sys.argv[1])
    if len(sys.argv) > 2:
        print(sys.argv[2])
        if os.path.exists(sys.argv[2]):
            USER_FILE = sys.argv[2]
            ctp_setting = load_json(USER_FILE)
        # else:
        #     if os.path.exists(sys.argv[2]):
        #     USER_FILE = sys.argv[2]
        #     print(f'{USER_FILE}.json')
        #     ctp_setting = load_json(f'{USER_FILE}.json')
        if os.path.exists(USER_FILE):
            ctp_setting = load_json(USER_FILE)
        os.chdir(sys.argv[1])
        if os.path.exists(USER_FILE):
            ctp_setting = load_json(USER_FILE)
else:
    os.chdir(WORKING_DIR)


print(ctp_setting)

SETTINGS["log.active"] = True
SETTINGS["log.level"] = INFO
SETTINGS["log.console"] = True

ctp_lv_setting = {
    "用户名": "154461",
    "密码": "winner410811",
    "经纪商代码": "9999",
    "交易服务器": "180.168.146.187:10130",
    "行情服务器": "180.168.146.187:10131",
    "产品名称": "simnow_client_test",
    "授权编码": "0000000000000000",
    "产品信息": "simnow_client"
}
ctp_lvtel_setting = {
    "用户名": "154461",
    "密码": "winner410811",
    "经纪商代码": "9999",
    "交易服务器": "180.168.146.187:10101",
    "行情服务器": "180.168.146.187:10111",
    "产品名称": "simnow_client_test",
    "授权编码": "0000000000000000",
    "产品信息": "simnow_client"
}

ctp_724_setting = {
    "用户名": "140589",
    "密码": "bc2021",
    "经纪商代码": "9999",
    "交易服务器": "180.168.146.187:10130",
    "行情服务器": "180.168.146.187:10131",
    "产品名称": "simnow_client_test",
    "授权编码": "0000000000000000",
    "产品信息": "simnow_client"
}
ctp_tel_setting = {
    "用户名": "140589",
    "密码": "bc2021",
    "经纪商代码": "9999",
    "交易服务器": "180.168.146.187:10101",
    "行情服务器": "180.168.146.187:10111",
    "产品名称": "simnow_client_test",
    "授权编码": "0000000000000000",
    "产品信息": "simnow_client"
}
ctp_724_2_setting = {
    "用户名": "132006",
    "密码": "Binchen@1314",
    "经纪商代码": "9999",
    "交易服务器": "180.168.146.187:10130",
    "行情服务器": "180.168.146.187:10131",
    "产品名称": "simnow_client_test",
    "授权编码": "0000000000000000",
    "产品信息": "simnow_client"
}

# os.environ['TZ'] = 'Asia/Shanghai'
# datetime.timetz()

# Chinese futures market trading period (day/night)
DAY_START = time(8, 45)
DAY_END = time(15, 16)

NIGHT_START = time(20, 45)
NIGHT_END = time(2, 45)


def check_trading_period():
    """"""
    current_time = datetime.now().time()

    return True
    # trading = False
    # if (
    #     (current_time >= DAY_START and current_time <= DAY_END)
    #     or (current_time >= NIGHT_START)
    #     or (current_time <= NIGHT_END)
    # ):
    #     trading = True

    # return trading


def run_child():
    """
    Running in the child process.
    """
    SETTINGS["log.file"] = True

    event_engine = EventEngine()
    main_engine = MainEngine(event_engine)
    main_engine.add_gateway(CtpGateway)
    # cta_engine = main_engine.add_app(CtaStrategyApp)
    # main_engine.write_log("主引擎创建成功")
    main_engine.add_app(DataRecorderApp)

    # log_engine = main_engine.get_engine("log")
    # event_engine.register(EVENT_CTA_LOG, log_engine.process_log_event)
    # main_engine.write_log("注册日志事件监听")
    try:
        main_engine.connect(ctp_setting, "CTP")
    except Exception as e:
        print(e)
    # cta_engine.init_engine()
    # main_engine.write_log("CTA策略初始化完成")

    # cta_engine.init_all_strategies()
    # sleep(60)   # Leave enough time to complete strategy initialization
    # main_engine.write_log("CTA策略全部初始化")

    # cta_engine.start_all_strategies()
    # main_engine.write_log("CTA策略全部启动")

    try:
        trading = True
        while trading:
            sleep(10)
            print("subprocess is running")
            trading = check_trading_period()
            # if not trading:
            #     print("关闭子进程")
            #     main_engine.close()
            #     sys.exit(0)

    except KeyboardInterrupt as results:
        print("关闭子进程")
        main_engine.close()
        sys.exit(0)


def run_parent():
    """
    Running in the parent process.
    """
    print("启动帐户分种数据守护父进程")

    child_process = None

    try:
        while True:
            trading = check_trading_period()
            if not trading:
                print("非交易时间,未启动子进程")
            # Start child process in trading period
            if trading and child_process is None:
                print("启动子进程")
                child_process = multiprocessing.Process(target=run_child)
                child_process.start()
                print("子进程启动成功")

            # 非记录时间则退出子进程
            if not trading and child_process is not None:
                if not child_process.is_alive():
                    child_process = None
                    print("子进程关闭成功")

            sleep(5)
    except KeyboardInterrupt as results:
        print("关闭进程")
        sys.exit(0)


if __name__ == "__main__":
    run_parent()
